﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BUS;
using LinQ_DTO;
using System.Xml.Linq;
using System.Xml;

namespace TemplateH4
{
    public partial class ChiTietSanPham : System.Web.UI.Page
    {

        bool LaMatTruoc = true;
        protected void Page_PreInit(object sender, EventArgs e)
        {
            String thm;
            thm = (string)Session["themeSelected"];
            if (thm != null)
            {
                Page.Theme = thm;
            }
            else
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(Server.MapPath("~/config.xml"));
                XmlNode root = doc.DocumentElement;
                String theme = root.SelectSingleNode("theme").ChildNodes[0].Value.Trim();
                Session.Add("themeSelected", theme);
                Page.Theme = theme;
            }

        }
        protected void Page_Load(object sender, EventArgs e)
        {

            if (IsPostBack == true)
            {
                int Mark = 0;

                RadioButton[] Radios = new RadioButton[5];
                Radios[0] = (RadioButton)this.grvChiTiet.Rows[0].FindControl("RadioButton1");
                Radios[1] = (RadioButton)this.grvChiTiet.Rows[0].FindControl("RadioButton2");
                Radios[2] = (RadioButton)this.grvChiTiet.Rows[0].FindControl("RadioButton3");
                Radios[3] = (RadioButton)this.grvChiTiet.Rows[0].FindControl("RadioButton4");
                Radios[4] = (RadioButton)this.grvChiTiet.Rows[0].FindControl("RadioButton5");
                for (int i = 0; i < 5; i++)
                {
                    if (Radios[i].Checked)
                        Mark = i + 1;
                }
                ViewState["Mark"] = Mark;
            }

            if (IsPostBack == false)
            {
                ///////////////////////////////Lưu sesion TAM THỜI SẼ BỎ SAU"]///////////
                //Session["IsLogin"] = 1;
                //Session["UserName"] = "royalnight102";


                ViewState["MatTruoc"] = LaMatTruoc;
                ViewState["Mark"] = 1;
                BindData();
                RadioButton Radio1 = (RadioButton)this.grvChiTiet.Rows[0].FindControl("RadioButton1");
                Radio1.Checked = true;

            }

        }

        private void BindData()
        {
            int MaSP = Convert.ToInt32(Request.QueryString["IdSP"]);
            SanPhamBUS Bus = new SanPhamBUS();
            NhanXetBUS NXBus = new NhanXetBUS();
            List<shop_sanpham> ListSP = Bus.LaySanPhamTheoMa(MaSP);
            this.grvChiTiet.DataSource = ListSP;
            string[] temp = { "MaLoaiSanPham" };
            grvChiTiet.DataKeyNames = temp;
            grvChiTiet.DataBind();

            BindCommentData();
        }

        private void BindCommentData()
        {

            int MaSP = Convert.ToInt32(Request.QueryString["IdSP"]);
            NhanXetBUS NXBus = new NhanXetBUS();
            List<shop_comment> ListComment = NXBus.LayNhanXetTheoMaSP(MaSP);
            grvComment.DataSource = ListComment;
            grvComment.DataBind();
        }

        protected void grvChiTiet_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void grvChiTiet_SelectedIndexChanged1(object sender, EventArgs e)
        {

        }

        protected void btnQuayMatSau_Click(object sender, ImageClickEventArgs e)
        {

            BindData();
            LaMatTruoc = (bool)ViewState["MatTruoc"];
            LaMatTruoc = !LaMatTruoc;
            ViewState["MatTruoc"] = LaMatTruoc;
            SanPhamBUS Bus = new SanPhamBUS();
            int MaSP = Convert.ToInt32(Request.QueryString["IdSP"]);
            shop_sanpham Sp = Bus.LaySanPhamTheoMa(MaSP)[0];
            Image ImgControl = (Image)this.grvChiTiet.Rows[0].FindControl("imgSP");

            XElement ImgNode;
            if (LaMatTruoc == true)
                ImgNode = Sp.HinhSanPham.Element("HinhTruoc");
            else
                ImgNode = Sp.HinhSanPham.Element("HinhSau");


            string ImgURL = string.Empty;
            if (ImgNode == null)
                ImgURL = "khong co hinh";
            else
                ImgURL = ImgNode.Value;
            ImgControl.AlternateText = ImgURL;
            ImgControl.ImageUrl = ImgURL;
        }

        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {
            
            if ((Session["IsLogin"] == null) || ((int)Session["IsLogin"] ==0))
            {
                Response.Redirect("~/BaoLoiChuaLogin.aspx");
                return;
            }



            BindData();
            int Mark = (int)ViewState["Mark"];

            List<shop_sanpham> ListSP = (List<shop_sanpham>)grvChiTiet.DataSource;
            shop_sanpham Sp = ListSP[0];

            shop_chamdiem NewRecord = new shop_chamdiem();
            NewRecord.MaSanPham = Sp.MaSanPham;
            NewRecord.Diem = Mark;

            SanPhamBUS Bus = new SanPhamBUS();
            Bus.ThemDiemChoSanPham(NewRecord);

            CauHinhBUS CHBus = new CauHinhBUS();
            UserBUS UsrBUS = new UserBUS();
            string UserName = (string)Session["UserName"];
            aspnet_User User = UsrBUS.LayUserTheoTen(UserName);
            aspnet_Membership Membership = User.aspnet_Membership;
            if (Membership.DiemTichLuy == null)
                Membership.DiemTichLuy = 0;
            Membership.DiemTichLuy += CHBus.LayDiemCongTichLuyBauChon();
            MembershipBUS MemBus = new MembershipBUS();
            MemBus.CapNhatDiemTichLuy(Membership);

            BindData();

        }

        protected void grvChiTiet_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                SanPhamBUS Bus = new SanPhamBUS();
                shop_sanpham Sp = (shop_sanpham)e.Row.DataItem;//(shop_sanpham)ListSP[e.Row.];

                //bind image
                Label lbDiem = (Label)e.Row.FindControl("lbDiem");

                int Diem = Bus.LayDiemCuaSanPham(Sp);
                lbDiem.Text = Diem.ToString() + " Điểm";

                int Mark = (int)ViewState["Mark"];
                RadioButton[] Radios = new RadioButton[5];
                Radios[0] = (RadioButton)e.Row.FindControl("RadioButton1");
                Radios[1] = (RadioButton)e.Row.FindControl("RadioButton2");
                Radios[2] = (RadioButton)e.Row.FindControl("RadioButton3");
                Radios[3] = (RadioButton)e.Row.FindControl("RadioButton4");
                Radios[4] = (RadioButton)e.Row.FindControl("RadioButton5");
                Radios[Mark - 1].Checked = true;


                //Bind Noi Dung khuyen mai
                Label KM = (Label)e.Row.FindControl("lbKM");
                string NoiDungKM = string.Empty;
                foreach (shop_sanpham_khuyenmai Km in Sp.shop_sanpham_khuyenmais)
                {
                    NoiDungKM += Km.shop_khuyenmai.NoiDung;
                }
                if (NoiDungKM == "")
                    KM.Text = "Không";
                else
                    KM.Text = NoiDungKM;

                //Bind Tinh trang san pham
                Label lbTinhTrang = (Label)e.Row.FindControl("lbTinhTrang");
                lbTinhTrang.Text = Sp.SoLuongCon > 0 ? "Còn hàng" : "Hết hàng";


            }


        }

        protected void btnNhanXet_Click(object sender, ImageClickEventArgs e)
        {
            int IsLogin = (int)Session["IsLogin"];
            if (IsLogin == 0)
            {
                Response.Redirect("~/Login.aspx");
                return;
            }

            UserBUS UsrBUS = new UserBUS();
            NhanXetBUS NXBUS = new NhanXetBUS();
            shop_comment cmt = new shop_comment();

            string UserName = (string)Session["UserName"];
            aspnet_User User = UsrBUS.LayUserTheoTen(UserName);

            int MaSp = Convert.ToInt32(Request.QueryString["IdSP"]);

            TextBox txtNhanXet = (TextBox)this.grvChiTiet.Rows[0].FindControl("txtNhanXet");
            string NhanXet = txtNhanXet.Text;

            cmt.UserId = User.UserId;
            cmt.MaSanPham = MaSp;
            cmt.NoiDung = NhanXet;
            cmt.NgayTao = DateTime.Now;
            cmt.TrangThai = false;

            NXBUS.ThemNhanXet(cmt);
            ClientScript.RegisterClientScriptBlock(GetType(), "Javascript", "<script>alert('Đã lưu nhận xét! Chờ kiểm duyệt!')</script>");
            txtNhanXet.Text = "";

            //Cap nhat diem tich luy trong CSDL
            CauHinhBUS CHBus = new CauHinhBUS();
            aspnet_Membership Membership = User.aspnet_Membership;
            if (Membership.DiemTichLuy == null)
                Membership.DiemTichLuy = 0;
            Membership.DiemTichLuy += CHBus.LayDiemCongTichLuyNhanXet();
            MembershipBUS MemBus = new MembershipBUS();
            MemBus.CapNhatDiemTichLuy(Membership);


        }

        protected void grvComment_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //Bind data vao list comment.
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                UserBUS UsrBus = new UserBUS();
                Label lbUserName = (Label)e.Row.FindControl("lbUser");
                Label lbDate = (Label)e.Row.FindControl("lbDate");
                TextBox txtComment = (TextBox)e.Row.FindControl("txtComment");

                shop_comment Cmt = (shop_comment)e.Row.DataItem;
                aspnet_User Usr = UsrBus.LayUserTheoMa(Cmt.UserId);

                string NgayTao = string.Format("{0}/{1}/{2}", Cmt.NgayTao.Day, Cmt.NgayTao.Month, Cmt.NgayTao.Year);
                lbUserName.Text = Usr.UserName;
                lbDate.Text = NgayTao;
                txtComment.Text = Cmt.NoiDung;

            }
        }

        protected void grvComment_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {

        }

        protected void grvComment_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void grvComment_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvComment.PageIndex = e.NewPageIndex;
            grvComment.EditIndex = -1;
            grvComment.SelectedIndex = -1;
        }

        protected void grvComment_PageIndexChanged(object sender, EventArgs e)
        {
            BindCommentData();
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            List<shop_sanpham> GioHang = (List<shop_sanpham>)Session["GioHang"];
            int MaSp = Convert.ToInt32(Request.QueryString["IdSP"]);

            SanPhamBUS BusSp = new SanPhamBUS();
            shop_sanpham Sp = BusSp.LaySanPhamTheoMa(MaSp)[0];

            if (GioHang == null)
                GioHang = new List<shop_sanpham>();

           TextBox txtSoLuong = (TextBox)this.grvChiTiet.Rows[0].FindControl("txtSoLuong");
           DropDownList cmbSize = (DropDownList)this.grvChiTiet.Rows[0].FindControl("cmbSize");
           int SoLuong;
            if(int.TryParse(txtSoLuong.Text,out SoLuong))
                if (SoLuong > 0)
                {
                    Sp.SoLuongNhap = SoLuong;
                    Sp.Size = cmbSize.SelectedValue;
                    Sp.GhiChu = "CS";
                    GioHang.Add(Sp);
                    Session["GioHang"] = GioHang;
                    //Page.ClientScript.RegisterStartupScript(this.GetType(), "messagebox", "alert('" + "Đã lưu sản phẩm vào giỏ hàng!" + "');");
                    ClientScript.RegisterClientScriptBlock(GetType(), "Javascript", "<script>alert('Đã lưu sản phẩm vào giỏ hàng!')</script>");
                    ClientScript.RegisterClientScriptBlock(GetType(), "Javascript", "<script>alert('Đã lưu nhận xét! Chờ kiểm duyệt!')</script>");
                }
                else
                    ClientScript.RegisterClientScriptBlock(GetType(), "Javascript", "<script>alert('Vui long nhap lai so luong!')</script>");

            

        }
    }
}
